import axios from 'axios'
import commonUrl from '../common/js/commonUrl.js'
// import {loadCityId} from '../common/js/cache.js'
import { getQueryString } from '../common/js/getQueryString.js'
import qs from 'qs'
import { loadCityCode, loadUserId, loadCity } from '../common/js/cache'

const url = `${commonUrl.apihost}index.php/home/`

// 获取openid
export function getOpenId () {
  return axios({
    method: 'GET',
    url: `${url}login/login?code=${getQueryString('code')}`
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

// 如果是用户通过搜索进入的页面  传  openId  给后台
export function passOpenId (id) {
  return axios({
    method: 'GET',
    url: `${url}login/login?openid=${id}`
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

// 获取首页公告，租售，求助列表
export function getVillageList (id) {
  return axios({
    method: 'GET',
    url: `${url}Index/recentAnnounce/?areas_id=${id}&city_code=${loadCityCode()}&city_name=${loadCity()}&user_id=${loadUserId()}`
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

// 通过微信jssdk 获取经纬度
export function getConfig () {
  const data = {
    url: window.location.href.split('#')[0]
  }
  return axios({
    method: 'POST',
    url: `${commonUrl.apihost}index.php/wx/wx_jssdk/getSignPackage`,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: qs.stringify(data)
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}

// 通过经纬度获取城市，小区
export function getAreasId (lng, lat) {
  return axios({
    method: 'GET',
    url: `${url}areas/position?lat=${lat}&lng=${lng}`
  }).then((res) => {
    return Promise.resolve(res.data)
  }).catch((err) => {
    return Promise.reject(err)
  })
}
